package com.ajx.platform.buildingmronitor.controller;

import com.ajx.platform.buildingmronitor.utils.DateUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.RandomAccessFile;

@RestController
public class TestSendVideoController {

    private Logger logger = LoggerFactory.getLogger(TestSendVideoController.class);

    @RequestMapping(value = "/testSendVideo/{sn}")
    public void TestSendVideo(@PathVariable String sn) throws Exception{
        long pos = 0;
        int size = 1024 * 200;
        String video = DateUtils.getCurrentTimeStr();
        JSONObject upload = upload(pos, size, sn, video);
        while (upload != null) {
            Boolean b = upload.getBoolean("resp");
            if (!b) {
                logger.info(upload.getString("msg"));
                break;
            } else {
                pos = upload.getLongValue("value");
                if (pos < 0) {
                    break;
                }
                upload = upload(pos, size, sn, video);
            }
        }
    }

    // 视频录像通过Http发送给服务器
    public JSONObject upload(long pos, int size,String sn,String video) throws Exception {
        JSONObject jsonResult = null;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse httpResponse = null;
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
        File file = new File("F:\\images\\test.mp4");
        long length = file.length();
        if (length < pos) {
            throw new RuntimeException("pos指针超出文件大小==>" + pos);
        }
        if (length < pos + size) {
            size = (int) (length - pos);
        }
        if (size == 0) {
            logger.info("文件已经上传完毕");
            return null;
        }
        byte[] buff = new byte[size];
        //RandomAccessFile同时将FileInputStream和FileOutputStream整合到一起，而且支持将从文件任意字节处读或写数据
        RandomAccessFile rfile = new RandomAccessFile(file, "r");
        //seek()方法定位指示器，方便从指示器的位置开始进行读写操作
        rfile.seek(pos);
        // 批量读取数据:一次从文件中读取buf数组length个字节,一次从文件中读取buf数组length个字节,返回值为实际读取到的字节数
        rfile.read(buff);
        rfile.close();
        logger.info(""+buff.length);
        HttpPost httpPost = new HttpPost("http://localhost:8721/eba/msg/ws/upload?devSN="+sn+"&video="+video+"&videoPos="+pos+"&videoLength="+length);
        httpPost.setConfig(requestConfig);
        httpPost.setEntity(new ByteArrayEntity(buff));
        //cameraSn,video
        httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        // 请求发送成功，并得到响应
        if (statusCode == HttpStatus.SC_OK) {
            String str = "";
            try {
                // 读取服务器返回过来的json字符串数据
                str = EntityUtils.toString(responseEntity, "utf-8");
                // 把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        httpClient.close();
        if (httpResponse != null) {
            httpResponse.close();
        }
        logger.info(jsonResult.toJSONString());
        return jsonResult;
    }
}
